<template>
  <view class="container">
    <form @submit="submitForm">
      <view class="form-item">
        <text>比赛名称：</text>
        <input type="text" placeholder="请输入比赛名称" v-model="competitionName" required />
      </view>
      <view class="form-item">
        <text>学号：</text>
        <input type="text" placeholder="请输入学号" v-model="studentId" @input="onInput" required />
      </view>
      <view class="form-item">
        <text>真实姓名：</text>
        <input type="text" placeholder="请输入真实姓名" v-model="realName" required />
      </view>
      <view class="form-item">
        <text>邮箱：</text>
        <input type="email" placeholder="请输入邮箱" v-model="email" required />
      </view>
      <view class="form-item">
        <text>电话：</text>
        <input type="tel" placeholder="请输入电话" v-model="phone" required />
      </view>
      <view class="form-item">
        <text>学院：</text>
        <input type="text" placeholder="请输入学院" v-model="college" required />
      </view>
      <view class="form-item">
        <text>班级：</text>
        <input type="text" placeholder="请输入班级" v-model="className" required />
      </view>
      <view class="form-item">
        <text>性别：</text>
        <radio-group @change="radioChange">
          <label>
            <radio value="1" :checked="gender === '1'"/>男
          </label>
          <label>
            <radio value="0" :checked="gender === '0'"/>女
          </label>
        </radio-group>
      </view>
      <button form-type="submit" class="submit-btn">报名</button>
    </form>
  </view>
</template>

<script>
export default {
  data() {
    return {
      access_token:'',
      touser: '',
      template_id: '',
      data: [],
      competitionName: '',
      studentId: '',
      realName: '',
      email: '',
      phone: '',
      college:'',
      className: '',
      gender: '1',
      debounceTimer: null,
      debounceDelay: 500,// 延迟时间，单位是毫秒
      startDate:'',
      sponsor:'',
      location:'',
      code:'',
    };
  },
  onLoad(option){
    this.competitionName = option.name;
    this.startDate = option.startDate;
    this.sponsor = option.sponsor;
    this.location = option.location;
    // this.user_login();
    
  },
  mounted(){
        this.authorize();
  },
  methods: {
    authorize(){
      uni.authorize({
        scope: 'scope.userInfo',
        success() {
            uni.getUserInfo({
              provider: 'weixin',
              success(e){
                console.log(e);
              }
            });
        }
        
    })
    },
    
     radioChange(e) {
          this.gender = e.detail.value;
        },
    mounted() {
      // 页面加载完成后获取数据
     // this.competitionName = option.name;
     
    },
     onInput(e) {
        clearTimeout(this.debounceTimer); // 清除之前的计时器
        this.debounceTimer = setTimeout(() => {
        this.getStudentInfo(e.target.value); // 延迟调用API
      }, this.debounceDelay);
       },

      getStudentInfo(studentId) {
          // 发起请求到后端
          this.$H.get(`user/studentInfo/${studentId}`).then(response => {
            // 假设后端返回的数据格式为 { name: "张三", class: "一班", ... }
            console.log(response);
  
            if (response.result) {
              this.realName = response.result.userName;
              this.phone = response.result.phone;
              this.college = response.result.college;
              this.className = response.result.className;
              this.gender = (response.result.sex).toString();
              this.email = response.result.email;
              // ...其他字段
            }else{
              uni.showToast({
                title: '该学号不存在',
                icon: 'none'
              });
            }
          }).catch(error => {
            // 处理错误
            console.error(error);
            uni.showToast({
              title: '该学号不存在',
              icon: 'none'
            });
          });
        },
   get_token() {
     return new Promise((resolve, reject) => {
       this.$H.get("competition/access_token").then(response => {
         console.log(response);
         // 假设 response 包含了获取的 access token
         this.access_token = response;
         resolve(response); // 成功时调用 resolve，并传递 response
       }).catch(error => {
         console.error(error);
         reject(error); // 失败时调用 reject，并传递 error
       });
     });
   },
   
   get_openid() {
     return new Promise((resolve, reject) => {
       console.log("code值：");
       console.log(this.code);
       this.$H.get(`competition/openid?code=${this.code}`).then(response => {
         console.log(response);
         // 假设 response 包含了获取的 openid
         this.touser = response;
         resolve(response); // 成功时调用 resolve，并传递 response
       }).catch(error => {
         console.error(error);
         reject(error); // 失败时调用 reject，并传递 error
       });
     });
   },
    
    user_login() {
    		 uni.login({
    			success(res) {
    				if (res.code) {
              // console.log(res.code);
    					this.code = res.code;
              uni.removeStorageSync("code");
              uni.setStorageSync("code",res.code);
              this.code = uni.getStorageSync("code");
               // console.log(this.code);
    				} else {
    					console.log('获取失败！' + res.errMsg)
    				}
    			}
    		})
    },
    
    notice() {
    		let self = this
    		//下方的thing1，thing2和其他，对应的是你选取模板的模板详情中的字段名称(可在小程序后台模板查看对应的字段，要和上面的字段一样)，需要更改成你自己的
    		const pushmsg = {
    			"touser": this.touser,
    			"template_id": "eA25VxzvZ-gIzYMPP7h7kM0QOAytLaLpzrjNOm-6JWA",
    			"data": {
    				"date3": {
    					"value": this.startDate
    				},
    				"thing4": {
    					"value":this.competitionName
    				},
    				"thing6": {
    					"value": this.location
    				},
    				"thing11": {
    					"value": this.sponsor
    				},
    				"thing7": {
    					"value": "请带好学生证件,演草纸和笔"
    				}
    			}
    		}
    		uni.request({
    			// 此处的mytoken
    			url: 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + this.access_token,
    			data: JSON.stringify(pushmsg),
    			method: 'POST',
    			success: function(res) {
    				 console.log('success');
    			}
    		})
    },

    
    submitForm(e) {
      e.preventDefault();
      if (this.competitionName && this.studentId && this.realName && this.email && this.phone && this.className ) {
//if(this.gender==='男') sex
        const data = {
          raceName: this.competitionName,
          sid: this.studentId,
          userName: this.realName,
          email: this.email,
          phone: this.phone,
          college: this.college,
          className: this.className,
          sex: this.gender
        };
        console.log(data);
         // this.user_login();
        this.enterCompetition(data);
      } else {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        });
      }
    },
    enterCompetition(data) {
      uni.request({
        // url: 'https://api.yhjoj.cn/app/user/studentsave',
         url: 'https://icpc.zut.edu.cn/app/user/studentsave',
        method: 'POST',
        data,
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 0) {
            uni.showToast({
              title: '报名成功！',
              icon: 'success'
            });
            // 弹出消息订阅提示
            this.subscribeMessage();
          } else {
            uni.showToast({
              title: '已经报名，请勿重复报名',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '网络错误，请检查网络连接',
            icon: 'none'
          });
        }
      });
    },
    subscribeMessage() {
      // 这里实现消息订阅的逻辑
      // 可以使用 uni.requestSubscribeMessage 等API
      this.user_login();
      this.code = uni.getStorageSync("code");
      console.log("code："+this.code);
      
      
     this.get_token()
         .then(() => {
           return this.get_openid();
         })
         .then(() => {
           return new Promise((resolve, reject) => {
             uni.requestSubscribeMessage({
               // 此处填写刚才申请模板的模板ID
               tmplIds: ['eA25VxzvZ-gIzYMPP7h7kM0QOAytLaLpzrjNOm-6JWA'],
               success: (res) => {
                 console.log(res);
                 resolve();
               },
               fail: (err) => {
                 reject(err);
               }
             });
           });
         })
         .then(() => {
           this.notice();
           console.log('订阅消息');
         })
         .catch((error) => {
           console.error(error);
         });

    }
  }
};
</script>

<style>
.container {
  padding: 20px;
}
.form-item {
  margin-bottom: 10px;
}
.submit-btn {
  margin-top: 20px;
  background-color: #007aff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
}
</style>